// Copyright 2017 The Chromium Authors. All rights reserved.
// Use of this source code is governed by a BSD-style license that can be
// found in the LICENSE file.

package com.ithaca.archime;

import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.ContextWrapper;
import android.content.Intent;
import android.content.IntentFilter;
import android.content.SharedPreferences;
import android.os.BatteryManager;
import android.os.Build.VERSION;
import android.os.Build.VERSION_CODES;
import android.os.Bundle;

import io.flutter.app.FlutterActivity;
import io.flutter.plugin.common.EventChannel;
import io.flutter.plugin.common.EventChannel.EventSink;
import io.flutter.plugin.common.EventChannel.StreamHandler;
import io.flutter.plugin.common.MethodChannel;
import io.flutter.plugin.common.MethodChannel.MethodCallHandler;
import io.flutter.plugin.common.MethodChannel.Result;
import io.flutter.plugin.common.MethodCall;
import io.flutter.plugin.common.PluginRegistry;
import io.flutter.plugins.GeneratedPluginRegistrant;
import io.flutter.plugins.MimcPlugin;

import java.util.UUID;

import cn.xsshome.taip.nlp.TAipNlp;
import cn.xsshome.taip.ocr.TAipOcr;

public class MainActivity extends FlutterActivity {
    private static final String METHOD_CHANNEL = "com.ithaca.archime/common";
    private static final String CHARGING_CHANNEL = "samples.flutter.io/charging";

    // Archime
    private static final String APP_ID = "2122411334";
    private static final String APP_KEY = "B2jXzKZLpeJWY8EU";

    private static Context mContext;

    public static Context getContext(){
        return mContext;
    }

    public static String getUserId(){
        String key = "userID";
        SharedPreferences preferences = getContext().getSharedPreferences("user", Context.MODE_PRIVATE);
        String value = preferences.getString(key, "");
        if (null == value || "".equals(value)){
            UUID uuid = UUID.randomUUID();
            setValue(preferences,key, uuid.toString());
            value = uuid.toString();
        }
        return value;
    }

    //修改
    private static void setValue(SharedPreferences preferences,String key,String value) {
        SharedPreferences.Editor editor = preferences.edit();
        editor.putString(key, value);
        editor.commit();
    }

    @Override
    public void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        if (mContext == null){
            mContext = getApplicationContext();
        }

        GeneratedPluginRegistrant.registerWith(this);
        registerCustomPlugin(this);

        new EventChannel(getFlutterView(), CHARGING_CHANNEL).setStreamHandler(
                new StreamHandler() {
                    private BroadcastReceiver chargingStateChangeReceiver;

                    @Override
                    public void onListen(Object arguments, EventSink events) {
                        chargingStateChangeReceiver = createChargingStateChangeReceiver(events);
                        registerReceiver(
                                chargingStateChangeReceiver, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
                    }

                    @Override
                    public void onCancel(Object arguments) {
                        unregisterReceiver(chargingStateChangeReceiver);
                        chargingStateChangeReceiver = null;
                    }
                }
        );

        new MethodChannel(getFlutterView(), METHOD_CHANNEL).setMethodCallHandler(
                new MethodCallHandler() {
                    @Override
                    public void onMethodCall(MethodCall call, Result result) {
                        if (call.method.equals("getBatteryLevel")) {
                            int batteryLevel = getBatteryLevel();

                            if (batteryLevel != -1) {
                                result.success(batteryLevel);
                            } else {
                                result.error("UNAVAILABLE", "Battery level not available.", null);
                            }
                        } else if (call.method.equals("textChat")) {
                            String question = call.argument("question");
                            System.out.println("onMethodCall:" + question);

                            try {
                                System.out.println("onMethodCall: 1111111111");
                                TAipNlp aipNlp = new TAipNlp(APP_ID, APP_KEY);
                                System.out.println("onMethodCall: 222222222222");
                                String session = "10000";
                                String strJson = aipNlp.nlpTextchat(session, question);
                                System.out.println("onMethodCall:" + strJson);
                                result.success(strJson);
                            } catch (Exception e) {
                                System.out.println("Exception:" + e.getMessage());
                            }

                        } else {
                            result.notImplemented();
                        }
                    }
                }
        );
    }

    private static void registerCustomPlugin(PluginRegistry registrar) {
        MimcPlugin.registerWith(registrar.registrarFor(MimcPlugin.CHANNEL));
    }

    private BroadcastReceiver createChargingStateChangeReceiver(final EventSink events) {
        return new BroadcastReceiver() {
            @Override
            public void onReceive(Context context, Intent intent) {
                int status = intent.getIntExtra(BatteryManager.EXTRA_STATUS, -1);

                if (status == BatteryManager.BATTERY_STATUS_UNKNOWN) {
                    events.error("UNAVAILABLE", "Charging status unavailable", null);
                } else {
                    boolean isCharging = status == BatteryManager.BATTERY_STATUS_CHARGING ||
                            status == BatteryManager.BATTERY_STATUS_FULL;
                    events.success(isCharging ? "charging" : "discharging");
                }
            }
        };
    }

    private int getBatteryLevel() {
        if (VERSION.SDK_INT >= VERSION_CODES.LOLLIPOP) {
            BatteryManager batteryManager = (BatteryManager) getSystemService(BATTERY_SERVICE);
            return batteryManager.getIntProperty(BatteryManager.BATTERY_PROPERTY_CAPACITY);
        } else {
            Intent intent = new ContextWrapper(getApplicationContext()).
                    registerReceiver(null, new IntentFilter(Intent.ACTION_BATTERY_CHANGED));
            return (intent.getIntExtra(BatteryManager.EXTRA_LEVEL, -1) * 100) /
                    intent.getIntExtra(BatteryManager.EXTRA_SCALE, -1);
        }
    }
}
